package com.example.java_gobang.api;

import com.example.java_gobang.game.MatchRequest;
import com.example.java_gobang.game.MatchResponse;
import com.example.java_gobang.game.Matcher;
import com.example.java_gobang.game.OnlineUserManager;
import com.example.java_gobang.model.UserInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Component
public class MatchApi extends TextWebSocketHandler {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private OnlineUserManager onlineUserManager;//上线管理器
    @Autowired
    private Matcher matcher;//匹配器
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("建立连接");
        try {
            //1.从session中拿取信息(已经将HTTP中的session转移到WebSocket)
            UserInfo userInfo = (UserInfo) session.getAttributes().get("user");
            if(userInfo == null){
                System.out.println("用户未登录");
                return;
            }
            //2.判断当前用户是否已经登录，如果已经登录则该次连接失败(不能顶号)
            if(onlineUserManager.getFromRoom(userInfo.getUserId()) != null){
                //当前用户已经登录
                MatchResponse response = new MatchResponse();
                response.setOk(false);
                response.setReason("当前用户已经登录");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
                //断开websocket连接
                session.close();
                return;
            }
            //3.拿到有效信息后把玩家设置成在线状态
            onlineUserManager.enterGameRoom(userInfo.getUserId(),session);
            System.out.println("玩家"+userInfo.getUsername()+"已经进入游戏大厅");
        }catch (NullPointerException e){
            e.printStackTrace();
        }

    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("发送消息："+message.getPayload());
        UserInfo userInfo = (UserInfo) session.getAttributes().get("user");
        String paylode = message.getPayload();
        //将传过来的JSON信息转换成Java对象
        MatchRequest request =  objectMapper.readValue(paylode,MatchRequest.class);
        //返回响应
        MatchResponse response = new MatchResponse();
        if(request.getMessage().equals("startMatch")){
            //进入匹配队列
            //先创建一个匹配队列将用户添加进去
            response.setOk(true);
            response.setMessage("startMatch");
            //将玩家加入到匹配队列中
            System.out.println("将玩家"+userInfo.getUsername()+"加入匹配队列");
            matcher.add(userInfo);

        }else if(request.getMessage().equals("stopMatch")){
            //退出匹配队列
            //创建一个匹配队列将用户移除
            response.setOk(true);
            response.setMessage("stopMatch");
            //将玩家移除匹配队列
            matcher.remove(userInfo);
            System.out.println("将玩家"+userInfo.getUsername()+"移除匹配队列");

        }else {
            response.setOk(false);
            response.setReason("非法匹配请求");
        }
        String json = objectMapper.writeValueAsString(response);
        session.sendMessage(new TextMessage(json));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("出现异常");
        try{
            UserInfo userInfo = (UserInfo) session.getAttributes().get("user");
            //将用户从map(游戏大厅)中退出
            WebSocketSession temSession = onlineUserManager.getFromRoom(userInfo.getUserId());
            if(temSession == session){
                onlineUserManager.exitGameRoom(userInfo.getUserId());
            }
            matcher.remove(userInfo);
        }catch (NullPointerException e){
            e.printStackTrace();
            MatchResponse response = new MatchResponse();
            response.setOk(false);
            response.setReason("用户未登录");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接断开");
        try{
            //1.从session中拿取信息(已经将HTTP中的session转移到WebSocket)
            UserInfo userInfo = (UserInfo) session.getAttributes().get("user");
            //当有两个浏览器同时登录一个账号时，要将后登录的下线，如果直接按照id下线由于两个浏览器用户id一样
            //所以会把第一次登录的用户给下线，所有我们在下线之前要先看看，游戏大厅里的用户和我们要下线的用户
            //是不是同一个，如果是说明我们下线的这个用户是成功登录的，如果不是则说明我们下线的这个用户是一个后登录的
            //不是游戏大厅里的那个
            //当我们要删除的用户和登录的用户一致时才删除
            WebSocketSession temSession = onlineUserManager.getFromRoom(userInfo.getUserId());
            if(temSession == session){
                onlineUserManager.exitGameRoom(userInfo.getUserId());
            }
            matcher.remove(userInfo);
        }catch (NullPointerException e){
            e.printStackTrace();
            //连接关闭后不能发送消息
//            MatchResponse response = new MatchResponse();
//            response.setOk(false);
//            response.setReason("用户未登录");
//            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }
    }
}
